package com.self.campussecondhandmarket.controller.user;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.self.campussecondhandmarket.common.BaseContext;
import com.self.campussecondhandmarket.entity.domain.Comment;
import com.self.campussecondhandmarket.entity.domain.Goods;
import com.self.campussecondhandmarket.entity.domain.Orders;
import com.self.campussecondhandmarket.entity.domain.User;
import com.self.campussecondhandmarket.entity.request.comment.Add;
import com.self.campussecondhandmarket.entity.request.comment.AdminAdd;
import com.self.campussecondhandmarket.entity.request.comment.CommentFilter;
import com.self.campussecondhandmarket.entity.request.comment.MyComment;
import com.self.campussecondhandmarket.entity.response.comment.AllComment;
import com.self.campussecondhandmarket.entity.response.comment.CommentList;
import com.self.campussecondhandmarket.resp.Result;
import com.self.campussecondhandmarket.service.CommentService;
import com.self.campussecondhandmarket.service.GoodsService;
import com.self.campussecondhandmarket.service.OrdersService;
import com.self.campussecondhandmarket.service.UserService;
import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Author: Vincent
 * <p> DateTime: 2024/4/13 21:10
 * <p> Description: 评论视图层
 * <p>
 **/
@RestController
@RequestMapping("/api/comment")
@CrossOrigin(origins = "http://localhost:9999", allowCredentials = "true")
public class CommentController {
	
	@Autowired
	CommentService commentService;
	@Autowired
	UserService userService;
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	OrdersService ordersService;
	
	/**
	 * 商品全部评论
	 */
	@PostMapping("/listByGoodsId")
	public Result listByGoods(@RequestBody @NonNull Map<String, Integer> dto) {
		List<Comment> comments = commentService.list(Wrappers.<Comment>lambdaQuery()
				.eq(Comment::getGoodsId, dto.get("goodId"))
		);
		
		List<CommentList> vo = comments.stream().map(o -> {
			CommentList list = new CommentList();
			User user = userService.getById(o.getUserId());
			list.setContent(o.getCommentContent());
			list.setCreateTime(o.getCreateTime());
			list.setAvatarUrl(user.getAvatarUrl());
			list.setName(user.getName());
			list.setStarNum(o.getStar());
			return list;
		}).toList();
		return Result.success(vo);
	}
	
	/**
	 * 我的评论
	 */
	@PostMapping("/myComment")
	public Result myComment(@RequestBody @NonNull MyComment dto) {
		
		List<Comment> list = commentService.list(Wrappers.<Comment>lambdaQuery()
				.eq(Comment::getUserId, BaseContext.getId())
		);
		List<com.self.campussecondhandmarket.entity.response.comment.MyComment> res = list.stream().map(o -> {
			Goods goods = goodsService.getById(o.getGoodsId());
			com.self.campussecondhandmarket.entity.response.comment.MyComment vo = new com.self.campussecondhandmarket.entity.response.comment.MyComment();
			vo.setContent(o.getCommentContent());
			vo.setStarNum(o.getStar());
			vo.setGoodName(goods.getName());
			vo.setCreateTime(o.getCreateTime());
			vo.setGoodImg(goods.getImg() == null ? "" : JSON.parseArray(goods.getImg(), String.class).get(0));
			vo.setGoodId(o.getGoodsId());
			return vo;
		}).toList();
		return Result.success(res);
	}
	
	/**
	 * 添加评论
	 */
	@Transactional
	@PostMapping("/add")
	public Result<String> add(@RequestBody @NonNull Add dto) {
		if (dto.getStatus() == null
				|| dto.getOrdersId() == null
				|| dto.getContent() == null
				|| dto.getStar() == null)
			return Result.error("参数错误");
		// 修改订单状态
		ordersService.changeStatus(dto.getOrdersId(), dto.getStatus());
		// 添加评论
		commentService.add(dto);
		return Result.success();
	}
	
	/**
	 * 管理员获取全部评论
	 */
	
	@PostMapping("/admin/all")
	public Result all() {
		List<AllComment> list = commentService.list().stream().map(o -> {
			AllComment vo = new AllComment();
			Orders orders = ordersService.getById(o.getOrdersId());
			Goods goods = goodsService.getById(o.getGoodsId());
			User user = userService.getById(o.getUserId());
			BeanUtils.copyProperties(o, vo);
			vo.setOrdersNo(orders.getOrdersNo());
			vo.setGoodsName(goods.getName());
			vo.setAvatarUrl(user.getAvatarUrl());
			vo.setUserName(user.getName());
			return vo;
		}).toList();
		return Result.success(list);
		
	}
	
	/**
	 * 管理员修改评论
	 *
	 * @param dto
	 * @return
	 */
	@PostMapping("/admin/edit")
	public Result edit(@RequestBody @NonNull Map<String, Object> dto) {
		Comment comment = new Comment();
		comment.setId((Integer) dto.get("id"));
		comment.setStar((Integer) dto.get("star"));
		comment.setCommentContent((String) dto.get("commentContent"));
		commentService.updateById(comment);
		return Result.success("修改成功");
	}
	
	/**
	 * 管理员添加评论
	 */
	@PostMapping("/admin/add")
	public Result add(@RequestBody @NonNull AdminAdd dto) {
		User user = userService.getById(dto.getUserId());
		if (user == null)
			return Result.error("用户不存在");
		Goods goods = goodsService.getById(dto.getGoodsId());
		if (goods == null)
			return Result.error("商品不存在");
		Orders orders = ordersService.getById(dto.getOrdersId());
		if (orders == null)
			return Result.error("订单不存在");
		List<Comment> list = commentService.list(Wrappers.<Comment>lambdaQuery()
				.eq(Comment::getOrdersId, orders.getOrdersNo())
		);
		if (list.size() > 1)
			return Result.error("该比订单已评价");
		Comment comment = new Comment();
		BeanUtils.copyProperties(dto, comment);
		commentService.save(comment);
		return Result.success();
	}
	
	@PostMapping("/admin/del/{id}")
	public Result del(@PathVariable Integer id) {
		commentService.removeById(id);
		return Result.success();
	}
	
	@PostMapping("/admin/filter")
	public Result filter(@RequestBody CommentFilter dto) {
		List<Integer> user = userService.list(Wrappers.<User>lambdaQuery()
				.eq(dto.getUserName() != null, User::getName, dto.getUserName())
		).stream().map(User::getId).toList();
		
		List<Integer> goods = goodsService.list(Wrappers.<Goods>lambdaQuery()
				.eq(dto.getGoodsName() != null, Goods::getName, dto.getGoodsName())
		).stream().map(Goods::getId).toList();
		
		List<Integer> orders = ordersService.list(Wrappers.<Orders>lambdaQuery()
				.eq(dto.getOrdersNo() != null, Orders::getOrdersNo, dto.getOrdersNo())
		).stream().map(Orders::getId).toList();
		
		List<CommentList> list1 = commentService.list(Wrappers.<Comment>lambdaQuery()
				.in(!user.isEmpty(), Comment::getUserId, user)
				.in(!goods.isEmpty(), Comment::getGoodsId, goods)
				.in(!orders.isEmpty(), Comment::getOrdersId, orders)
				.eq(dto.getStar() != null, Comment::getStar, dto.getStar())
		).stream().map(o -> {
			CommentList list = new CommentList();
			User temp = userService.getById(o.getUserId());
			list.setContent(o.getCommentContent());
			list.setCreateTime(o.getCreateTime());
			list.setAvatarUrl(temp.getAvatarUrl());
			list.setName(temp.getName());
			list.setStarNum(o.getStar());
			return list;
		}).toList();
		return Result.success(list1);
	}
}
